package cm.auth;

import cm.utils.HttpClientUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
//import com.alibaba.nacos.common.model.RestResultUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 *过滤
 */
@Slf4j
@Component
@WebFilter(urlPatterns = "/*")
public class LoginUserFilter implements Filter {

    @Value("${usr.info.url:https:/xxx}")
    private String userInfoUrl;

    @Value("${vhr.tokenAuth:false}")
    private boolean tokenAuth;

    private final ObjectMapper objectMapper = new ObjectMapper();

    private static final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Value("${vhr.whiteMenu:/vhr/work-order/workOrder/faultOrder/save,/vhr/work-order/workOrder/maintainOrder/save}")
    private String whiteMenu;

    private final String defaultWhiteMenu = "/**/**/doc.html," +
            "/**/**/swagger-resources," +
            "/**/**/webjars/**," +
            "/**/**/swagger-resources/configuration/ui," +
            "/**/**/v2/api-docs,/**/doc.html," +
            "/**/swagger-resources," +
            "/**/webjars/**," +
            "/**/swagger-resources/configuration/ui," +
            "/**/v2/api-docs";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("LoginUserFilter 获取初始请求tsp的用户接口：{}", userInfoUrl);
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        if (!tokenAuth){
            chain.doFilter(request, response);
            return;
        }
        String str = StringUtils.isEmpty(this.whiteMenu)? defaultWhiteMenu : defaultWhiteMenu.concat(",").concat(this.whiteMenu);
        String[] menus = str.split(",");
        HttpServletRequest req = (HttpServletRequest)request;
        String servletPath = req.getRequestURI();
        for (String excludedPath : menus) {
            String uriPattern = excludedPath.trim();
            if (antPathMatcher.match(uriPattern, servletPath)) {
                chain.doFilter(request, response);
                return;
            }
        }
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        // 测试给出工号
        String employNo = httpRequest.getHeader("employNo");
        String employName = httpRequest.getHeader("employName");
        if (!StringUtils.isEmpty(employNo)){
            UserInfo user = UserInfo.builder().employeeNumber(employNo).userName(employName).build();
            log.info("获取到用户信息为：{}", JSON.toJSONString(user));
            UserContext.setCurrentUserInfo(user);
            chain.doFilter(request, response);
            System.out.println("线程执行结束>>>>>>>>>>");
            return;
        }
        // 获取Token
        String token = httpRequest.getHeader("Token");
        log.info("=================>获取到的Token:{}", token);
        if (StringUtils.isEmpty(token)){
            // 重定向
            ServletOutputStream outputStream = response.getOutputStream();
//            outputStream.write(objectMapper.writeValueAsString(RestResultUtils.failedWithMsg(300, "user has not get Token.....")).getBytes(StandardCharsets.UTF_8));
            outputStream.flush();
            return;
        }
        // 根据当前用户获取用户信息
        try {
            String url = String.format("%s?t=%s", userInfoUrl, System.currentTimeMillis());
            String result = HttpClientUtil.sendRequestByGetTypeWithToken(url, token);
            JSONObject jsonObject = JSON.parseObject(result);
            String msg = jsonObject.getString("msg");
            int code = jsonObject.getInteger("code");
            JSONObject jsb = jsonObject.getJSONObject("user");
            if ("success".equals(msg) && code == 0){
                UserInfo userInfo = UserInfo.builder()
                        .userId(jsb.getInteger("userId"))
                        .userName(jsb.getString("realname"))
                        .employeeNumber(jsb.getString("userNo"))
                        .email(jsb.getString("email"))
                        .phone(jsb.getString("mobile"))
                        .build();
                log.info("获取到用户信息为：{}", JSON.toJSONString(userInfo));
                if (StringUtils.isEmpty(jsb.getString("userNo"))){
                    // 重定向
                    ServletOutputStream outputStream = response.getOutputStream();
                    response.setCharacterEncoding(StandardCharsets.UTF_8.name());
//                    outputStream.write(objectMapper.writeValueAsString(RestResultUtils.failedWithMsg(300, "请联系管理员添加工号.....")).getBytes(StandardCharsets.UTF_8));
                    outputStream.flush();
                    return;
                }
                UserContext.setCurrentUserInfo(userInfo);
            }else {
                // 重定向
                ServletOutputStream outputStream = response.getOutputStream();
//                outputStream.write(objectMapper.writeValueAsString(RestResultUtils.failedWithMsg(300, "Get user info failure .....")).getBytes(StandardCharsets.UTF_8));
                outputStream.flush();
                return;
            }
        } catch (IOException e) {
            log.error("获取用户信息失败：", e);
            throw new RuntimeException(e);
        }
        chain.doFilter(request, response);
    }
}
